#include <iostream>
#include <memory>
#include <cstdlib>
#include "Protocol.hpp"
#include "Server.hpp"

int main(int argc, char *argv[], char *env[])
{
    if (argc != 3)
    {
        std::cout << argv[0] << " ip port " << std::endl;
        exit(1);
    }

    std::string ip = argv[1];
    uint16_t port = atoi(argv[2]);

    std::unique_ptr<ns_sock::Sock> sock(new ns_sock::Sock());
    // 创建网络套接字
    int sockfd = sock->Socket();

    // 申请连接
    if (!sock->Connect(sockfd, port, ip))
    {
        close(sockfd);
        exit(2);
    }

    std::string message;
    
    bool flag=true;
    while (flag)
    {
        ns_protocol::Request request;

        std::cout << "请输入 x op y # ";
        std::cin >> request._x >> request._op >> request._y;

        // 反序列化+EnCode
        std::string ser = request.Serialization();
        ser = ns_protocol::EnCode(ser);
        std::cout<<"EnCode success"<<std::endl;

        // 写
        ns_protocol::Send(sockfd, ser);

        while (true)
        {
            // 读
            if (!ns_protocol::Recv(sockfd, &message))
            {
                flag=false;
                break;
            }

            std::string str=ns_protocol::DeCode(message);
            if(str.empty())
            {
                continue;
            }
            std::cout<<"DeCode success"<<std::endl;

            ns_protocol::Response responce;
            responce.Deserialization(str);

            std::cout << "code: " << responce._code << " result: " << responce._result << std::endl;
            break;
        }
    }

    close(sockfd);

    return 0;
}